package com.ningxun.pagent.bus.service.basewechatuser.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ningxun.pagent.bus.domain.wechatuser.BaseWechatUser;
import com.ningxun.pagent.common.core.domain.entity.SysUser;
import com.ningxun.pagent.common.core.domain.model.LoginUser;
import com.ningxun.pagent.common.utils.DateUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.UUID;

@Service
public class WechatUserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private BaseWechatUserServiceImpl baseWechatUserService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //  验证用户身份查询openid 将openid放入userName中

        BaseWechatUser wechatUser = baseWechatUserService.queryBaseWechatUserByopenid(username);
//        需要判断对象是否为空
        if (ObjectUtils.isEmpty(wechatUser)){
            BaseWechatUser baseWechatUser = new BaseWechatUser();
            baseWechatUser.setOpenId(username);
            baseWechatUser.setUserStatus(1L);
            baseWechatUser.setCreateTime(DateUtils.getNowDate());
            String uuname = "微信用户" + UUID.randomUUID();
            uuname = uuname.substring(0, Math.min(uuname.length(), 25));
            baseWechatUser.setNikeName(uuname);
            //        如果对象为空，那么就让表中新增加一个他teenuser

            baseWechatUserService.save(baseWechatUser);
        }
        LambdaQueryWrapper<BaseWechatUser> wrapper = new LambdaQueryWrapper<BaseWechatUser>()
                .select(BaseWechatUser::getUserId)
                .eq(BaseWechatUser::getOpenId , username);
        BaseWechatUser userid = baseWechatUserService.getOne(wrapper);

//        如果不为空，就让表中数据提交
        SysUser user = new SysUser();
        user.setUserName(username);
        return new LoginUser(userid.getUserId(), 0L, user, new HashSet<>());
    }
}
